package org.itboys.ace.web;

import com.google.common.collect.Lists;
import org.apache.commons.lang.StringUtils;
import org.itboys.admin.tools.AdminCookieHolder;
import org.itboys.commons.CommonConstants;
import org.itboys.commons.utils.ajax.AjaxUtils;
import org.itboys.commons.utils.number.ToNumberUtils;
import org.itboys.commons.utils.time.TimeUtils;
import org.itboys.framework.query.JsonPageUtils;
import org.itboys.framework.spring.controller.BaseController;
import org.itboys.seller.constant.CaliforniaSiteConstant;
import org.itboys.seller.dto.DetailInfoRecordVo;
import org.itboys.seller.dto.DetailInfoVO;
import org.itboys.seller.dto.MatchRecordVO;
import org.itboys.seller.entity.SiteUser;
import org.itboys.seller.meta.InfoPublish;
import org.itboys.seller.meta.MatchInfo;
import org.itboys.seller.service.CaliforniaSiteUserService;
import org.itboys.seller.service.InfoPublishService;
import org.itboys.seller.service.MatchInfoService;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author hzliangchong1@corp.netease.com
 *         Date 2016/10/23.
 */
@RestController
@RequestMapping("/publish")
public class InfoPublishController extends BaseController {

    @Resource
    private InfoPublishService infoPublishService;
    @Resource
    private CaliforniaSiteUserService californiaSiteUserService;
    @Resource
    private MatchInfoService matchInfoService;

    @RequestMapping("/providerHelp")
    public void providerHelp(int amount, Integer payType1, Integer payType2, Integer payType3,
                          HttpServletRequest request, HttpServletResponse response) {
        if (amount < 20000 || amount > 2000000 || amount % 20000 != 0) {
            AjaxUtils.renderText(response, "必须是200至20000之间的金额且必须是200的整数倍");
            return;
        }
        String accountId= AdminCookieHolder.getAdminUserName();
        if (!infoPublishService.canProvideHelp(accountId)) {
            AjaxUtils.renderText(response, "-1");
            return;
        }
        SiteUser user = californiaSiteUserService.getAdminUser(accountId);
        if (user.getState() == CaliforniaSiteConstant.TYPE_ZERO) {
            AjaxUtils.renderText(response, "-2");
            return;
        }
        InfoPublish infoPublish = new InfoPublish();

        infoPublish.setAccountId(accountId);
        infoPublish.setHelpType(CaliforniaSiteConstant.HelpType.PROVIDER);
        infoPublish.setState(CaliforniaSiteConstant.InfoState.PUBLISH);
        infoPublish.setAmount(amount);
        infoPublish.setCreateTime(System.currentTimeMillis());
        infoPublish.setUpdateTime(System.currentTimeMillis());
        int payType = 0;
        payType = payType1 == 0 ? payType : payType | payType1;
        payType = payType2 == 0 ? payType : payType | payType2;
        payType = payType3 == 0 ? payType : payType | payType3;
        infoPublish.setPayType(payType);

        infoPublishService.insert(infoPublish);
        AjaxUtils.renderText(response, CommonConstants.SUCCESS);
        logger.info("member {} try provider help, amount {}", accountId, amount / 100);
    }

    @RequestMapping("/acceptHelp")
    public void acceptHelp(int amount, HttpServletRequest request,
                           HttpServletResponse response) {
        if (amount < 0 || amount % 10000 != 0) {
            AjaxUtils.renderText(response, "必须是100的整数倍");
            return;
        }
        String accountId= AdminCookieHolder.getAdminUserName();
        if (!infoPublishService.canAcceptHelp(accountId)) {
            AjaxUtils.renderText(response, "-1");
            return;
        }
        InfoPublish infoPublish = new InfoPublish();

        infoPublish.setAccountId(accountId);
        infoPublish.setHelpType(CaliforniaSiteConstant.HelpType.ACCEPT);
        infoPublish.setState(CaliforniaSiteConstant.InfoState.PUBLISH);
        infoPublish.setAmount(amount);
        infoPublish.setCreateTime(System.currentTimeMillis());
        infoPublish.setUpdateTime(System.currentTimeMillis());
        int payType = 0;
        infoPublish.setPayType(payType);

        infoPublishService.insert(infoPublish);
        AjaxUtils.renderText(response, CommonConstants.SUCCESS);
        logger.info("member {} try accept help, amount {}", accountId, amount / 100);
    }

    @RequestMapping("/infoPublishList")
    public void indexAllList(int pageNo, int pageSize,
                             HttpServletRequest request, HttpServletResponse response) {
        String accountId= AdminCookieHolder.getAdminUserName();
        int offset = Math.max(0, (pageNo - 1) * pageSize);
        List<MatchInfo> infoPublishList = matchInfoService.queryInfo(accountId, offset, pageSize);
        List<MatchRecordVO> voList = infoPublishList.stream().map(p -> {
            MatchRecordVO vo = new MatchRecordVO();
            vo.setMatchId(p.getId());
            vo.setMatchState(p.getState());
            vo.setProviderAcc(p.getProviderAcc());
            vo.setAcceptAcc(p.getAcceptAcc());
            if (p.getProviderAcc().equals(accountId)) {
                vo.setHelpType(CaliforniaSiteConstant.HelpType.PROVIDER);
            } else if (p.getAcceptAcc().equals(accountId)) {
                vo.setHelpType(CaliforniaSiteConstant.HelpType.ACCEPT);
            }
            vo.setDate(TimeUtils.format(new Date(p.getUpdateTime()), "yyyy-MM-dd HH:mm:ss"));
            vo.setRemainTime(getTimeStr((System.currentTimeMillis() - p.getUpdateTime()) / 1000));
            vo.setAmount(p.getAmount() / 100);
            return vo;
        }).collect(Collectors.toList());
        JsonPageUtils.renderJsonPage(infoPublishService.totalInfo(accountId), voList, response);
    }

    @RequestMapping("/getRemainTime")
    public void getRemainTIme(long matchId, HttpServletRequest request,
                              HttpServletResponse response) {
        MatchInfo info = matchInfoService.getById(matchId);
        if (info == null) {
            AjaxUtils.renderText(response, "");
            return;
        }
        if (info.getState() == CaliforniaSiteConstant.InfoState.MATCHED ||
                info.getState() == CaliforniaSiteConstant.InfoState.WAIT_CONFIRM) {
            long time = (System.currentTimeMillis() - info.getUpdateTime()) / 1000;
            AjaxUtils.renderText(response, getTimeStr(time));
            return;
        }
        AjaxUtils.renderText(response, "");
    }

    private String getTimeStr(long time) {
        StringBuilder sb = new StringBuilder();
        time = Math.max(0, 3600 * 24 - time);
        if (time == 0) {
            return "0天00:00:00";
        }
        long day = time / 3600 / 24;
        long hour = (time % (3600 * 24)) / 3600;
        long min = (time % 3600) / 60;
        long sec = (time % 60);
        sb.append(day).append("天")
                .append(hour < 10 ? "0" + hour : hour)
                .append(":").append(min < 10 ? "0" + min : min)
                .append(":").append(sec < 10 ? "0" + sec : sec);
        return sb.toString();
    }

    @RequestMapping("/getInfo")
    public void getInfo(long matchId, HttpServletRequest request,
                              HttpServletResponse response) {
        MatchInfo matchInfo = matchInfoService.getById(matchId);
        if (matchInfo == null) {
            AjaxUtils.renderText(response, "");
            return;
        }
        DetailInfoVO detailInfoVO = new DetailInfoVO();
        detailInfoVO.setOrderId("R" + matchInfo);
        detailInfoVO.setAmount(matchInfo.getAmount() / 100);
        SiteUser provider = californiaSiteUserService.getAdminUser(matchInfo.getProviderAcc());
        SiteUser accepter = californiaSiteUserService.getAdminUser(matchInfo.getAcceptAcc());
        DetailInfoRecordVo providerVo = new DetailInfoRecordVo();
        BeanUtils.copyProperties(provider, providerVo);
        if (provider.getRecUserId() != 0) {
            SiteUser rec = californiaSiteUserService.getAdminUserByUserId(provider.getRecUserId());
            providerVo.setManagerNick(rec.getMemberName());
            providerVo.setManagerPhone(rec.getPhone());
        }
        DetailInfoRecordVo acceptVo = new DetailInfoRecordVo();
        BeanUtils.copyProperties(accepter, acceptVo);
        if (accepter.getRecUserId() != 0) {
            SiteUser rec = californiaSiteUserService.getAdminUserByUserId(accepter.getRecUserId());
            acceptVo.setManagerNick(rec.getMemberName());
            acceptVo.setManagerPhone(rec.getPhone());
        }
        detailInfoVO.setGetMoneyInfo(acceptVo);
        detailInfoVO.setPlayMoneyInfo(providerVo);
        AjaxUtils.renderJson(response, detailInfoVO);
    }

    /**
     * 上传图片
     * @return
     */
    @RequestMapping("/postImg")
    public void postImg( @RequestParam(required=true) MultipartFile img,
                         long matchId,
                         HttpServletRequest request, HttpServletResponse response) {
        matchInfoService.playMoneyConfrim(matchId, img);
        AjaxUtils.renderText(response, CommonConstants.SUCCESS);
    }

    /**
     * 客户留言
     */
    @RequestMapping("/leaveMsg")
    public void leaveMsg(long matchId, String msg,
                         HttpServletRequest request, HttpServletResponse response) {
        matchInfoService.leaveMsg(matchId, msg);
        AjaxUtils.renderText(response, CommonConstants.SUCCESS);
    }
}
